package com.carsite.webapp.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.carsite.Constants;
import com.carsite.model.Item;
import com.carsite.model.Material;
import com.carsite.model.Order;
import com.carsite.model.OrderNo;
import com.carsite.model.Product;
import com.carsite.service.ItemManager;
import com.carsite.service.MaterialManager;
import com.carsite.service.OrderManager;
import com.carsite.service.OrderNoManager;
import com.carsite.service.ProductManager;
import com.carsite.webapp.form.OrderForm;

/**
 * Action class to handle CRUD on a Order object
 * 
 * @struts.action name="orderForm" path="/orders" scope="request"
 *                validate="false" parameter="method" input="mainMenu"
 * @struts.action name="orderForm" path="/editOrder" scope="request"
 *                validate="false" parameter="method" input="list"
 * @struts.action name="orderForm" path="/saveOrder" scope="request"
 *                validate="true" parameter="method" input="edit"
 * @struts.action-set-property property="cancellable" value="true"
 * @struts.action-forward name="edit" path="/WEB-INF/pages/orderForm.jsp"
 * @struts.action-forward name="list" path="/WEB-INF/pages/orderList.jsp"
 * @struts.action-forward name="formlist"
 *                        path="/WEB-INF/pages/orderformList.jsp"
 * @struts.action-forward name="search" path="/orders.html" redirect="true"
 * @struts.action-forward name="editOrder_itemList"
 *                        path="/WEB-INF/pages/editOrder_itemList.jsp"
 * @struts.action-forward name="mes" path="/WEB-INF/pages/mes.jsp"
 * 
 */
public final class OrderAction extends BaseAction {
	public ActionForward cancel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("search");
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'delete' method");
		}

		ActionMessages messages = new ActionMessages();
		OrderForm orderForm = (OrderForm) form;

		// Exceptions are caught by ActionExceptionHandler
		OrderManager mgr = (OrderManager) getBean("orderManager");

		mgr.removeOrder(orderForm.getOrderId());

		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
				"order.deleted"));

		// save messages in session, so they'll survive the redirect
		saveMessages(request.getSession(), messages);

		return mapping.findForward("search");
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'edit' method");
		}

		OrderForm orderForm = (OrderForm) form;

		// if an id is passed in, look up the user - otherwise
		// don't do anything - user is doing an add
		if (null != orderForm && null != orderForm.getOrderId()) {
			OrderManager mgr = (OrderManager) getBean("orderManager");
			Order order = mgr.getOrder(orderForm.getOrderId());
			orderForm = (OrderForm) convert(order);
			updateFormBean(mapping, request, orderForm);
		}
		if (null == orderForm) {
			orderForm = new OrderForm();
			updateFormBean(mapping, request, orderForm);
		}
		return mapping.findForward("edit");
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'save' method");
		}

		// Extract attributes and parameters we will need
		ActionMessages messages = new ActionMessages();
		OrderForm orderForm = (OrderForm) form;
		boolean isNew = ("".equals(orderForm.getOrderId()) || orderForm
				.getOrderId() == null);

		OrderNoManager Nomgr = (OrderNoManager) getBean("orderNoManager");
		OrderManager mgr = (OrderManager) getBean("orderManager");

		MaterialManager materialManager = (MaterialManager) getBean("materialManager");
		ProductManager productManager = (ProductManager) getBean("productManager");

		Order order = (Order) convert(orderForm);
		if (null == order.getOrderId()) {

			order.setStatus(0);
			OrderNo oNo = Nomgr.getOrderNO();
			Long no = 1L;
			if (null != oNo) {
				no = oNo.getNum();
				oNo.setNum(no + 1);
				Nomgr.saveOrderNo(oNo);
			} else {
				OrderNo oOn = new OrderNo();
				oOn.setNum(2L);
				Nomgr.saveOrderNo(oOn);
			}
			// 1出货单 2收货单
			int type = order.getType();
			if (type == 1) {
				Calendar c = Calendar.getInstance();
				String orderNo = "C-" + c.get(Calendar.YEAR) + "-"
						+ (c.get(Calendar.MONTH) + 1) + "-"
						+ c.get(Calendar.DATE) + "-" + no;
				order.setOrderNo(orderNo);
			} else {
				Calendar c = Calendar.getInstance();
				String orderNo = "J-" + c.get(Calendar.YEAR) + "-"
						+ (c.get(Calendar.MONTH) + 1) + "-"
						+ c.get(Calendar.DATE) + "-" + no;
				order.setOrderNo(orderNo);
			}
			// order.setOrderNo(no.toString());

		} else {
			Integer type = order.getType();
		}
		mgr.saveOrder(order);

		// add success messages
		if (isNew) {
			messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
					"order.added"));

			// save messages in session to survive a redirect
			saveMessages(request.getSession(), messages);
			List materialList = materialManager.getMaterials(null);
			List productList = productManager.getProducts(null);
			request.setAttribute("materialList", materialList);
			request.setAttribute("productList", productList);
			request.setAttribute("orderId", order.getOrderId());
			return mapping.findForward("editOrder_itemList");
			// request.getRequestDispatcher("").forward(request, response);

			// return mapping.findForward("search");
		} else {
			messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
					"order.updated"));
			saveMessages(request, messages);

			return mapping.findForward("edit");
		}
	}

	public ActionForward saveItems(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println("saveItems");
		// String[] materialIds=request.getParameterValues("materialId");
		// String[] productIds=request.getParameterValues("productId");
		OrderManager mgr = (OrderManager) getBean("orderManager");
		ItemManager itemMgr = (ItemManager) getBean("itemManager");

		MaterialManager materialManager = (MaterialManager) getBean("materialManager");
		ProductManager productManager = (ProductManager) getBean("productManager");

		Map map = request.getParameterMap();
		String[] materialIds = (String[]) map.get("productId");
		String[] productIds = (String[]) request
				.getParameterValues("productId");
		String orderId = ((String[]) map.get("orderId"))[0];
		Order order = mgr.getOrder(orderId);
		for (int i = 0; null != materialIds && i < materialIds.length; i++) {
			String materialId = materialIds[i];
			Material material = materialManager.getMaterial(materialId);

			String materialNum = ((String[]) map.get(materialId
					+ "_material_num"))[0];
			Item item = new Item();
			item.setNum(new Integer(materialNum));
			item.setSn(material.getSn());
			item.setTitle(material.getTitle());
			item.setType(material.getTypes());
			item.setOrder(order);
			order.addItem(item);
			item.setOrder(order);
			mgr.saveOrder(order);

			itemMgr.saveItem(item);

			System.out.println(materialNum);
		}
		for (int i = 0; null != productIds && i < productIds.length; i++) {
			String productId = productIds[i];
			Product product = productManager.getProduct(productId);
			String productNum = ((String[]) map.get(productId + "_product_num"))[0];
			Item item = new Item();
			item.setNum(new Integer(productNum));
			item.setSn(product.getSn());
			item.setTitle(product.getTitle());
			item.setType(product.getTypes());
			order.addItem(item);
			item.setOrder(order);

			itemMgr.saveItem(item);

			System.out.println(productNum);
		}
		// mgr.saveOrder(order);
		request.setAttribute("mes", "单据已成功增加！");
		return mapping.findForward("mes");
	}

	public ActionForward search(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug("Entering 'search' method");
		}
		String step = request.getParameter("step");
		if ("0".equals(step)) {
			return mapping.findForward("formlist");
		}
		OrderForm orderForm = (OrderForm) form;
		Order order = (Order) convert(orderForm);

		OrderManager mgr = (OrderManager) getBean("orderManager");
		request.setAttribute(Constants.ORDER_LIST, mgr.getOrders(order));

		return mapping.findForward("list");
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return search(mapping, form, request, response);
	}

	public ActionForward getOrderListByCondition(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String orderNo = request.getParameter("orderNo");
		OrderManager oMgr = (OrderManager) this.getBean("orderManager");
		ItemManager iMgr = (ItemManager) this.getBean("itemManager");
		// Order order=oMgr.getOrder(orderNo);
		List orderList = oMgr.getOrdersByOrderNo(orderNo);
		// Item item=new Item();
		// item.setOrder(order);
		// List
		// itemList=iMgr.getItemsByOrderId(order.getOrderId().toString());//iMgr.getItems(item);
		// Iterator it=order.getItems().iterator();
		// while(it.hasNext()){
		// String title=((Item)it.next()).getTitle();
		// System.out.println(title);
		// }
		// List orderList=new ArrayList();
		// orderList.add(order);
		request.setAttribute(Constants.ORDER_LIST, orderList);
		return mapping.findForward("formlist");

	}
}
